//
//  MainViewController.swift
//  weibo
//
//  Created by 吴婷婷 on 15/11/3.
//  Copyright © 2015年 wutingting. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
        
    // MARK: - 按钮监听方法
    @objc private func clickComposedButton(){
        var vc: UIViewController
        if UserAccountViewModel.sharedUserAccount.userLogon {
            vc = ComposeViewController()
        } else {
            vc = OAuthViewController()
        }
        let nav = UINavigationController(rootViewController: vc)
        presentViewController(nav, animated: true, completion: nil)
        
    }
    
    
    //MARK: - 视图声明周期方法
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view
        addChildViewControllers()
        
//        print(tabBar.subviews)
        
        setUpComposedButton()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.bringSubviewToFront(composedButton)
    }
    
    //MARK: - 懒加载控件
    private lazy var composedButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")

    
}
// MARK: - 设置界面
extension MainViewController{
    
    private func setUpComposedButton() {
        
        tabBar.addSubview(composedButton)
        
        let count = childViewControllers.count
        
        let w = tabBar.bounds.width / CGFloat(count) - 1
        
        composedButton.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        
        composedButton.addTarget(self, action: "clickComposedButton", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    
    ///添加所有控制器
    func addChildViewControllers() {
        
        tabBar.tintColor = UIColor.orangeColor()
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        
        //占位用
        addChildViewController(UIViewController())
        
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
        
        
    }
    ///添加控制器
    func addChildViewController(vc:UIViewController, title:String, imageName:String) {
        
        vc.title = title
        
        vc.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
}
